package arduino;

import java.util.Vector; 
import java.util.concurrent.*;

public class MessageQueue {
	//private ArrayBlockingQueue<MyPressureMessage> myQueue ;
	private Vector<MyMessage> myQueue;
	private int messageCapacity = 100;
	
	
	MessageQueue(){
		myQueue = new Vector<MyMessage>(messageCapacity);
		//myQueue = new ArrayBlockingQueue<MyPressureMessage>(messageCapacity);
	}
	
	public synchronized void InsertMessage(MyMessage pMsg){
		while( myQueue.size() >= 100 ){		// at most 100 messages at one time
			try{
				wait();						// wait if 100 messages in the queue
			}
			catch(InterruptedException exception ){
				exception.printStackTrace();
			}
		}
		myQueue.add(pMsg);
		notify();							// get up consumer if you are waiting
	}
	
	public synchronized Vector<MyMessage> GetAllMessages(){
		Vector<MyMessage> readMessages = new Vector<MyMessage>();
		
		while( myQueue.isEmpty() ){
			try{
				//go to sleep consumer since there are no messages
				wait();
			}
			catch(InterruptedException exception){
				exception.printStackTrace() ;
			}
		}
		// read all messages from the queue
		while( !myQueue.isEmpty() ){
			readMessages.add(myQueue.firstElement());
			myQueue.remove(0);
		}			
		// notify if producer was sleeping
		notify();
		return readMessages;
	}	
}
